import React, { useState, useImperativeHandle, useEffect  } from 'react';
import { Form, Button, Input, Checkbox, Collapse, Row, Col, Modal, message } from 'antd';
import { ExclamationCircleOutlined } from '@ant-design/icons';

import styles from './styles/menu.module.css';

import { useMainContext } from '@contexts/MainContext'

const { Panel } = Collapse;
const { confirm } = Modal;

// 获取已选中菜单的menuKeyCode
const getTreeCheckedId = menuTree => {
    const menuArray = JSON.parse(JSON.stringify(menuTree))
    let menuKeys = []
    for (const item of menuArray) {
      const {indeterminate, checked, children} = item
  
      if (!indeterminate && !checked) continue //没有选中的效果 直接退出本次循环
  
      if (checked || indeterminate) {
        menuKeys.push(item.keyCode)
      }
  
      if (children && children.length) {
        const childrenIds = getTreeCheckedId(children)
        menuKeys = menuKeys.concat(childrenIds)
      }
    }
    return menuKeys
}

const Menu = (props) => {
  const { isButtomShow } = useMainContext()

  const { menuRef, onFinish, menuItems } = props
  const newMenuItems = JSON.parse(JSON.stringify(menuItems))

  const [form] = Form.useForm()
  const [menuTree, setMenuTree] = useState([]);// 菜单树
  const [activeKey, setSctiveKey] = useState([]); // 折叠面板展开的keys

  // 折叠面板改变的回调
  const onCollapseChange = (newActiveKey) => {
    setSctiveKey(newActiveKey);
  }

  useEffect(() => {
    if (!menuItems.length) return
    
    setMenuTree(newMenuItems)

    // 展开全部面板
    const newActiveKey = newMenuItems[0]?.children?.filter(item => item.children.length)
    setSctiveKey(newActiveKey.map(item => item.keyCode))

  },[menuItems])

  // 暴露给外部组件的方法
  useImperativeHandle(menuRef, () => ({
    // 切换角色时， 更新菜单树
    update: (data) => {
        const { roleName, roleId, ownerMenuKeyCodeList } = data
        form.setFieldValue('roleName', roleName) // 回显角色名称
        form.setFieldValue('roleId', roleId) // 更新角色需要roleCode
        setCheckbox(menuTree, ownerMenuKeyCodeList) // 根据角色的 ownerMenuKeyCodeList 勾选对应的功能权限
        setMenuTree([...menuTree])
    }
  }))

  /**
   * 设置上层的 Checkbox 选中效果
   * @param {*} menuId 上层菜单的id
   * @param {*} menulist 菜单数组
   */
  const setUpperMenu = (menuId, menulist) => {
    for (const menuItem of menulist) {
      const { supperMenuId, keyCode, children } = menuItem

      if (keyCode === menuId) {
        menuItem.checked = children.every(item => item.checked)
        menuItem.indeterminate = menuItem.checked ? false : children.some(item => item.checked || item.indeterminate)
        setUpperMenu(supperMenuId, menuTree)
        break;
      }
      
      if (children && children.length) {
        setUpperMenu(menuId, children)
      }
    }
  }
 
  /**
   * 设置下层的 Checkbox 选中效果
   * @param {*} checked //当前的Checkbox是否选中
   * @param {*} item 当前的菜单的数据
   * @returns 
   */
  const setUnderMenu = (checked, item) => {
    item.checked = checked
    item.indeterminate = checked ? false : item.indeterminate
    const {children} = item
    if (!children) return
    for (const childrenItem of children) {
      setUnderMenu(checked, childrenItem)
    }
  };

  // Checkbox组件的 poroos
  const boxProps = item => {
    return {
      indeterminate: item?.indeterminate,
      checked: item?.checked,
      onChange: event => {
        if (!form.getFieldValue('roleId')) {
          return message.info('请先选择需要编辑的角色！')
        }
        const checked = event.target.checked
        setUnderMenu(checked, item)
        setUpperMenu(item?.supperMenuId, menuTree)
        setMenuTree([...menuTree])
      },
    }
  }

  const PanelHeader = props => {
    const attrs = {
      ...boxProps(props), 
    }
    return (
      <span onClick={ e => e.stopPropagation()}>
        <Checkbox {...attrs}>{props.keyName}</Checkbox>
      </span>
    )
  }

  // 切换角色，回显已配置的权限
  const setCheckbox = (menulist, roleList = [], ) => {

    for (const menuItem of menulist) {
        const { supperMenuId, keyCode, children } = menuItem
  
        menuItem.checked = roleList.some(item => keyCode === item)
        setUpperMenu(supperMenuId, menuTree)
        
        if (children && children.length) {
          setCheckbox(children, roleList)
        }
      }

  }

  // 保存
  const handleFinish = (params) => {
    confirm({
      title: '温馨提示：',
      icon: <ExclamationCircleOutlined />,
      content: '您确定要保存该角色的权限吗?',
      okText: '确定',
      cancelText: '取消',
      onOk() {
        return new Promise(async (resolve, reject) => {
          // console.log('ownerMenuKeyCodeList==>' ,getTreeCheckedId(menuTree));
          const CheckedIds = getTreeCheckedId(menuTree)
          if (CheckedIds.includes('070300')) {
            CheckedIds.push('070303','070304')
          }
          // console.log(CheckedIds);
          // console.log(Array.from(new Set(CheckedIds)));
          await onFinish({...params, ownerMenuKeyCodeList: Array.from(new Set(CheckedIds)) })
          resolve()

        })
      },
    });

  };

  const isHidden = (key) => {
    switch (key) {
      case '070303': return true
      case '070304': return true
    
      default: return false
    }
  }

  return (
    <div className={styles.menuBox}>
      <Form
        name="form"
        form={form}
        onFinish={handleFinish}
      >
        <Row align="middle" gutter='16'>
          <Col flex={1}>
            <Form.Item label="角色code" name="roleId" hidden>
              <Input disabled/>
            </Form.Item>
            <Form.Item label="角色名称" name="roleName" wrapperCol={{ span: 8 }}>
              <Input disabled/>
            </Form.Item>
          </Col>
          <Col>
            <Form.Item>
              {isButtomShow('630205') && <Button type="primary" htmlType="submit" disabled={!form.getFieldValue('roleId')}>保存</Button>
              }
            </Form.Item>
          </Col>
          </Row>
        {/* <Form.Item>
          <Row align="middle" justify="space-between">
            <Col>
              <span className={styles.text}>选择所需功能权限</span>
              <Checkbox {...boxProps(menuTree[0])}>全选</Checkbox>
            </Col>
            <Col><Button type="primary" htmlType="submit">{currentRoleCode ? '保存' : '新增'}</Button></Col>
          </Row>
        </Form.Item> */}
      </Form>

      <Collapse expandIconPosition='end' activeKey={activeKey} onChange={onCollapseChange}>

        {menuTree.map(panelItem => {
          const {children: panelChildren} = panelItem
          return (
            <Panel header={PanelHeader(panelItem)} key={panelItem.keyCode}>

              {panelChildren?.map(item => {
                const {children: itemChildren} = item
                return (
                  <div className={styles.menuBoxItem} key={item.keyCode}>
                    <div className={styles.checkedAll}>
                      <Checkbox {...boxProps(item)}>{item.keyName}</Checkbox>
                    </div>
                    <Row className={styles.checkboxGroup}>

                      {itemChildren?.map(groupItem => {
                        return ( isHidden(groupItem.keyCode) ? null :
                          <Col span={6} className={styles.checkboxGroupItem} key={groupItem.keyCode}>
                            <Checkbox {...boxProps(groupItem)}>{groupItem.keyName}</Checkbox>
                          </Col>
                        )
                      })}

                    </Row>
                  </div>
                )
              })}

            </Panel>
          )
        })}

      </Collapse>
    </div>
  );
};
export default React.memo(Menu);
